package lib.rv

import androidx.databinding.BindingAdapter
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import lib.rv.ap.*
import lib.rv.tools.RvUtils

/**
 *  author: luoXiong
 *  e-mail: 382060748@qq.com
 *  date: 2021/9/8 19:01
 *  version: 1.0
 *  desc:
 */

// Rv 列表
var def_mvi_item_click_variable = BR.click
var def_mvi_item_data_variable = BR.item
/**
 *  @param layoutFlag 默认是1
 *          如果是1, 创建 LinearLayout 垂直方向
 *          如果==0,会创建 LinearLayout,并设置 水平方向
 *          如果大于1,会创建 GridLayout,并设置spanCount
 *          如果是负数,不设置layout
 *          如果大于等于12,说明是瀑布流布局,取个位数作为spanCount
 *          GridLayoutManager.SpanSizeLookup
 */
@BindingAdapter(
    value = [
        "mvi_b_rv_adapter",
        "mvi_b_rv_items",
        "mvi_b_rv_vtd_list",
        "mvi_b_rv_itemIds",
        "mvi_b_rv_item_decoration",
        "mvi_b_rv_item_clickEvent",
        "mvi_b_rv_layout_span",
        "mvi_b_rv_SpanSizeLookup"],
    requireAll = false
)
// <M : IViewTypeModel>  <V : ViewDataBinding, M : IViewTypeModel>
fun <M : IViewTypeModel> RecyclerView.set_rv_adapter(
    adapter: BaseRvAdapter<M>?,
    items: List<Any>?,
    viewTypeDelegateList: List<ViewTypeDelegate<ViewDataBinding, M>>?,
    itemIds: BaseRvAdapter.ItemIds<in M>?,
    divider: RecyclerView.ItemDecoration?,
    itemClick: ClickListener? = null,
    layoutFlag: Int = RecyclerView.VERTICAL,
    spanLookup: GridLayoutManager.SpanSizeLookup? = null
) {
    if (this.adapter != null) return
    if (items == null) return
    var newAdapter = adapter
    if (newAdapter == null) {
        newAdapter = object : BaseRvAdapter<M>() {
            override fun onCreateVHForAll(b: ViewDataBinding) {
                if (itemClick != null) {
                    b.setVariable(def_mvi_item_click_variable, itemClick)
                }
            }

            override fun onBindVHForAll(b: ViewDataBinding, m: M) {
                b.setVariable(def_mvi_item_data_variable, m)
            }

            override fun addViewTypeDelegate(manager: ViewTypeDelegateManager<M>) {
                if (viewTypeDelegateList != null) {
                    manager.addAll(viewTypeDelegateList)
                }
            }
        }
    }
    // 设置布局管理
    RvUtils.set_rv_layoutmanager(this, layoutFlag, spanLookup)
    // 设置分割线
    RvUtils.set_rv_divider(this, divider)
    // 设置数据源
    newAdapter.setItems(items as List<M>)
    // 设置item的id
    newAdapter.setItemIds(itemIds)
    // 设置适配器
    this.adapter = newAdapter
}
